package com.itheima.edu.info.manager.dao;

import com.itheima.edu.info.manager.domain.Student;

public class StudentDao implements BaseStudentDao{
    //1.创建一个数组,用于装数据
    public static Student[] arr = new Student[5];


    static{
        Student stu1 = new Student("heima001","张三","23","1997-11-11");
        Student stu2 = new Student("heima002","李四","24","1998-12-12");
        arr[0]=stu1;
        arr[1]=stu2;
    }
    @Override
    public boolean addSTtudent(Student student) {

        //2.将数据装到数组中
        //2.1 将数据装到null元素的对应位置,找到位置,立马结束循环
        //2.2 假设数组中没有null元素
        int index = -1;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == null) {
                index = i;
                break;
            }
        }

        if (index == -1) {
            //都装满了
            return false;
        } else {
            //没装满,开始装数据
            arr[index] = student;
            return true;
        }
    }

    @Override
    public Student[] findAllStudent() {
        //将数组返回
        return arr;
    }

    @Override
    public void deleteStudentByid(String id) {
        //1.查找id在数组中对象的id相同的对象索引
        int index = getIndex(id);
        //2.用null替换对应的对象元素
        arr[index]=null;
    }

    @Override
    public int getIndex(String id){
        //1.假设数组中的对象id与输入的id不符
        int index = -1;
        //2.得出id所在对象的索引
        for (int i = 0; i < arr.length; i++) {
            if(arr[i] != null && arr[i].getId().equals(id)){
                index = i;
                break;
            }
        }
        //3.返回索引
        return index;
    }

    @Override
    public void updateDao(String updateId, Student newStu) {
        //1.查找id在数组中对象的id相同的对象索引
        int index = getIndex(updateId);
        //2.修改对象
        arr[index] = newStu;
    }
}
